package com.yj.web.scheduler;

import backMsg.BackMsgSender;
import com.yj.web.dao.mapper.AdminUserMapper;
import com.yj.web.dao.mapper.FundraisingProjectMapper;
import com.yj.web.dao.po.admin.FundraisingProject;
import com.yj.web.dao.po.admin.Message;
import com.yj.web.dao.po.admin.ProjectTip;
import com.yj.web.dao.po.admin.RepayPlan;
import com.yj.web.help.IdGenerater;
import com.yj.web.service.MessageService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Service;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.util.Date;
import java.util.HashSet;
import java.util.Set;

/**
 * Created by yanlinyang on 2017/8/3.
 */
@Service("msgNoticeTask")
public class MsgNoticeTask {
    private static final Logger logger = LoggerFactory.getLogger(MsgNoticeTask.class);

    @Autowired
    private FundraisingProjectMapper fundraisingProjectMapper;
    @Autowired
    private AdminUserMapper adminUserMapper;
    @Autowired
    private MessageService messageService;

    @Scheduled(cron="0 0/15 * * * ?")
    public void repayNotice () {
        //当天提醒还款
        LocalDate date = LocalDate.now();
        LocalDateTime dateTimeStart = date.atTime(0,0,0);
        LocalDateTime dateTimeEnd = date.atTime(23,59,59);
        Set<RepayPlan> repayPlen = fundraisingProjectMapper.repayTodayUnpaid2(dateTimeStart.toString().replace("T", " "), dateTimeEnd.toString().replace("T", " "));
        if (null != repayPlen && repayPlen.size() > 0) {
            for (RepayPlan repayPlan : repayPlen) {
                FundraisingProject project = fundraisingProjectMapper.findFundraisingProjectById(repayPlan.getFund_project_id());

                ProjectTip tip = new ProjectTip();
                tip.setUser_id(project.getBorrower_id());
                tip.setTitle(project.getTitle() + "项目还款提醒（当天）");
                String msg = "您的借款项目\"" + project.getTitle() + "\"，进行第" + repayPlan.getCurrent_period() +
                        "期还款，预计还款" + repayPlan.getRepay_amount() + "元（含本金" + repayPlan.getPrincipal_amount() +
                        "元，利息" + repayPlan.getInterest_amount() + "），请按时还款。";
                tip.setMsg_body(msg);
                tip.setFund_project_id(repayPlan.getFund_project_id());
                tip.setProject_type(0);
                tip.setMsg_type(1);
                String tipId = IdGenerater.generateId("11");
                tip.setId(tipId);
                fundraisingProjectMapper.insertProjectTip(tip);//发起人

                //亿美短信提醒
                String msgContent = "【医诺筹款】您的筹款项目\"" + project.getTitle() + "\"，本期应还金额" + repayPlan.getRepay_amount() + "元，请登录医诺公众号：医诺在线，及时偿还，若已还清请忽略。";
                String phone = project.getBorrower_phone();
//                String templateCode = "";
//                String templateParam = "{\"title\":\""+ project.getTitle() +"\", \"repay_amount\":\""+ repayPlan.getRepay_amount() +"\"}";
                try {
                    BackMsgSender.sendSingleSms(msgContent, phone);
                    logger.info("项目还款提醒（当天）{} - {}, 时间{}", phone,msgContent, LocalDateTime.now());

                    Message message = new Message();
                    message.setReceiverStr(phone);
                    Set<String> receivers = new HashSet<>();
                    receivers.add(phone);
                    message.setReceivers(receivers);
                    message.setNumber(1);
                    message.setContent(msgContent);
                    message.setStatus(1);
                    message.setType(2);
                    messageService.insertMessage(message);
                } catch (Exception e) {
                    e.printStackTrace();
                    throw new RuntimeException(e);
                }

            }
        }

        //三天前提醒还款
        LocalDate date3After = date.plusDays(3);
        dateTimeStart = date3After.atTime(0,0,0);
        dateTimeEnd = date3After.atTime(23,59,59);
        repayPlen = fundraisingProjectMapper.repayTodayUnpaid2(dateTimeStart.toString().replace("T", " "), dateTimeEnd.toString().replace("T", " "));
        if (null != repayPlen && repayPlen.size() > 0) {
            for (RepayPlan repayPlan : repayPlen) {
                FundraisingProject project = fundraisingProjectMapper.findFundraisingProjectById(repayPlan.getFund_project_id());

                ProjectTip tip = new ProjectTip();
                tip.setUser_id(project.getBorrower_id());
                tip.setTitle(project.getTitle() + "项目还款提醒（三天前）");
                String msg = "您的借款项目\"" + project.getTitle() + "\"预计在" + date3After + "(三天后），进行第" + repayPlan.getCurrent_period() +
                        "期还款，预计还款" + repayPlan.getRepay_amount() + "元（含本金" + repayPlan.getPrincipal_amount() +
                        "元，利息" + repayPlan.getInterest_amount() + "），请按时还款。";
                tip.setMsg_body(msg);
                tip.setFund_project_id(repayPlan.getFund_project_id());
                tip.setProject_type(0);
                tip.setMsg_type(1);
                String tipId = IdGenerater.generateId("11");
                tip.setId(tipId);
                fundraisingProjectMapper.insertProjectTip(tip);//发起人

                //亿美短信提醒
                String msgContent = "【医诺筹款】您的筹款项目\"" + project.getTitle() + "\"预计在" + date3After + "(三天后），进行第" + repayPlan.getCurrent_period() +
                        "期偿还，预计应还金额" + repayPlan.getRepay_amount() + "元（含本金" + repayPlan.getPrincipal_amount() +
                        "元，利息" + repayPlan.getInterest_amount() + "），请登录医诺公众号：医诺在线，按时偿还。";

                String phone = project.getBorrower_phone();
//                String templateCode = "";
//                String templateParam = "{\"title\":\""+ project.getTitle() +"\", \"date\":\""+ date +"\", \"period\":\""+ repayPlan.getCurrent_period() +"\", \"repay_amount\":\""+ repayPlan.getRepay_amount() +"\", \"principal\":\""+ repayPlan.getPrincipal_amount() +"\", \"interest\":\""+ repayPlan.getInterest_amount() +"\"}";

                try {
                    BackMsgSender.sendSingleSms(msgContent, phone);
                    logger.info("项目还款提醒（三天前）{} - {}, 时间{}", phone,msgContent, LocalDateTime.now());

                    Message message = new Message();
                    message.setReceiverStr(phone);
                    Set<String> receivers = new HashSet<>();
                    receivers.add(phone);
                    message.setReceivers(receivers);
                    message.setNumber(1);
                    message.setContent(msgContent);
                    message.setStatus(1);
                    message.setType(2);
                    messageService.insertMessage(message);
                } catch (Exception e) {
                    e.printStackTrace();
                    throw new RuntimeException(e);
                }
            }
        }

        //逾期提醒
        LocalDateTime today = date.atTime(0,0,0);
        repayPlen = fundraisingProjectMapper.repayOverdue(today.toString().replace("T", " "));
        if (null != repayPlen && repayPlen.size() > 0) {
            for (RepayPlan repayPlan : repayPlen) {
                FundraisingProject project = fundraisingProjectMapper.findFundraisingProjectById(repayPlan.getFund_project_id());

                //计算逾期天数
                SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                try {
                    Date plan_repay_at = sdf.parse(repayPlan.getPlan_repay_at());
                    long days = date.toEpochDay() - plan_repay_at.getTime()/(1000 * 60 * 60 * 24)-1;

                ProjectTip tip = new ProjectTip();
                tip.setUser_id(project.getBorrower_id());
                tip.setTitle(project.getTitle() + "项目逾期提醒");
                String msg = "您的借款项目\"" + project.getTitle() + "\"，第" + repayPlan.getCurrent_period() +
                        "期预计归还" + repayPlan.getRepay_amount() + "元（含本金" + repayPlan.getPrincipal_amount() +
                        "元，利息" + repayPlan.getInterest_amount() + "），已逾期" + days + "天，请珍惜您的信用按时归还项目款项。";
                tip.setMsg_body(msg);
                tip.setFund_project_id(repayPlan.getFund_project_id());
                tip.setProject_type(0);
                tip.setMsg_type(1);
                String tipId = IdGenerater.generateId("11");
                tip.setId(tipId);
                fundraisingProjectMapper.insertProjectTip(tip);//发起人

                // 亿美短信提醒
                String msgContent = "【医诺筹款】您的筹款项目\"" + project.getTitle() + "\"，第" + repayPlan.getCurrent_period() +
                        "期预计归还" + repayPlan.getRepay_amount() + "元（含本金" + repayPlan.getPrincipal_amount() +
                        "元，利息" + repayPlan.getInterest_amount() + "），已逾 期" + days + "天，请珍惜您的信用按时归还项目款项。";
                String phone = project.getBorrower_phone();
//                String templateCode = "";
//                String templateParam = "{\"title\":\""+ project.getTitle() +"\", \"date\":\""+ date +"\", \"period\":\""+ repayPlan.getCurrent_period() +"\", \"repay_amount\":\""+ repayPlan.getRepay_amount() +"\", \"principal\":\""+ repayPlan.getPrincipal_amount() +"\", \"interest\":\""+ repayPlan.getInterest_amount() +"\"}";
                try {
                    BackMsgSender.sendSingleSms(msgContent, phone);
                    logger.info("项目逾期发送短信提醒用户{} - {}, 时间{}", phone,msgContent,LocalDateTime.now());

                    Message message = new Message();
                    message.setReceiverStr(phone);
                    Set<String> receivers = new HashSet<>();
                    receivers.add(phone);
                    message.setReceivers(receivers);
                    message.setNumber(1);
                    message.setContent(msgContent);
                    message.setStatus(1);
                    message.setType(2);
                    messageService.insertMessage(message);
                } catch (Exception e) {
                    e.printStackTrace();
                    throw new RuntimeException(e);
                }
                } catch (ParseException e) {
                    e.printStackTrace();
                }
            }
        }
    }
}
